import Foundation
import TunnelKitOpenVPNCore
import TunnelKitCore
import TunnelKitManager
import TunnelKitOpenVPN
import NetworkExtension

class VpnManager: NSObject {
    static let shared = VpnManager()

    private let vpn = NetworkExtensionVPN()
    private let fileManager = FileManager.default
    private var vpnConfigFile: URL
    private override init() {
        let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        guard let documentsDirectory = urls.first else {
            fatalError("找不到文件路径")
        }
        self.vpnConfigFile = documentsDirectory.appendingPathComponent("5188.ovpn")
        
        super.init()
        
        copyConfigFileToDocuments()
    }
    
    
    func fileURLInDocumentsDirectory(for fileName: String) -> URL? {
        // 获取文档目录的URL
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        // 构建文件的完整路径URL
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        
        // 检查文件是否存在
        if FileManager.default.fileExists(atPath: fileURL.path) {
            return fileURL
        } else {
            return nil
        }
    }
    
    private func copyConfigFileToDocuments() {
        if let bundlePath = Bundle.main.path(forResource: "5188", ofType: "ovpn") {
            let destinationPath = vpnConfigFile.path

            if !fileManager.fileExists(atPath: destinationPath) {
                do {
                    try fileManager.copyItem(atPath: bundlePath, toPath: destinationPath)
                    print("文件已存在")
                } catch {
                    print("复制文件错误 \(error)")
                }
            } else {
                print("文件已存在")
            }
        } else {
            print("Config file not found in bundle")
        }
    }
    

    
    func makeConfig() -> OpenVPN.ProviderConfiguration? {
       
        
        let index = UserDefaultsManager1.shared.getInt(forKey: "vpnList")
        
        //let index = -1
        let path: String

        if #available(iOS 16.0, *) {
            if index == -1{
                path = vpnConfigFile.path()
            }else{
                path = fileURLInDocumentsDirectory(for: "hot\(index).ovpn")!.path()

            }
        } else {
            if index == -1{
                path = vpnConfigFile.path
            }else{
                path = fileURLInDocumentsDirectory(for: "hot\(index - 5 ).ovpn")!.path

            }
        }
        
        guard FileManager.default.fileExists(atPath: path) else {
            return nil
        }
        
        print("文件路径: \(path)")
        
        do {
            let fileContents = try String(contentsOfFile: path, encoding: .utf8)
          //  print("文件内容\(fileContents)")
        } catch {
            print("Failed to read VPN configuration file: \(error)")
            return nil
        }
        
        guard let builder = try? OpenVPN.ConfigurationParser.parsed(fromURL: vpnConfigFile) else {
            print("Failed to parse VPN configuration file")
            return nil
        }
        
        let cfg = builder.configuration
        var providerConfiguration = OpenVPN.ProviderConfiguration("QuickBooster - VPN Proxy Master", appGroup: "group.xianban.vpn", configuration: cfg)
        providerConfiguration.shouldDebug = true
        providerConfiguration.masksPrivateData = false
        return providerConfiguration
    }

    
    // 连接
    func connect() {
       
        guard let cfg = makeConfig() else {
            print("连接失败")
            return
        }
        Task {
            let extra = NetworkExtensionExtra()
            do {
                try await vpn.reconnect(
                    "org.xianban.ppn.test.EncryptoVpnTunnel",
                    configuration: cfg,
                    extra: extra,
                    after: .seconds(2)
                )
                print("连接无异常")
            } catch {
                print("连接错误: \(error)")
            }
        }
    }
    
  
     func disconnect() {
        Task {
            await vpn.disconnect()
            print("关闭连接")
        }
    }
    
    
    public func reconnect() {
        disconnect()
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.connect()
        }
    }
}

class UserDefaultsManager1 {
    static let shared = UserDefaultsManager1()
    
    private init() {}
    
    // 保存String值
    func setString(_ value: String, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getString(forKey key: String) -> String? {
        let value = UserDefaults.standard.string(forKey: key)
        return value ?? "null"
    }
    
    func setInt(_ value: Int, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getInt(forKey key: String) -> Int {
        let value = UserDefaults.standard.object(forKey: key) as? Int
        return value ?? -1
    }
    
    func setBool(_ value: Bool, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getBool(forKey key: String) -> Bool {
        let value = UserDefaults.standard.object(forKey: key) as? Bool
        return value ?? false
    }
    
    // 保存对话记录为JSON格式
    func saveChatMessage(role: Bool, content: String) {
        var chatMessages = UserDefaults.standard.array(forKey: "chatMessages") as? [[String: String]] ?? []
        let newMessage = [
            "role": role ? "user" : "assistant",
            "content": content
        ]
        chatMessages.append(newMessage)
        UserDefaults.standard.set(chatMessages, forKey: "chatMessages")
    }
    
    // 获取保存的对话记录
    func getChatMessages() -> [[String: String]] {
        let chatMessages = UserDefaults.standard.array(forKey: "chatMessages") as? [[String: String]] ?? []
        return chatMessages
    }
    
    func getChatMessagesJSON() -> String {
           let chatMessages = getChatMessages()
           if let jsonData = try? JSONSerialization.data(withJSONObject: chatMessages, options: .prettyPrinted) {
               return String(data: jsonData, encoding: .utf8) ?? "[]"
           }
           return "[]"
       }
    func clearChatMessages() {
            UserDefaults.standard.removeObject(forKey: "chatMessages")
        }
    func isChatMessageCountGreaterThanTen() -> Bool {
            let chatMessages = getChatMessages()
        print("count",chatMessages.count)
            return chatMessages.count < 11
        }
}
